package com.emergency.embackend.service.impl;


import cn.hutool.json.JSONUtil;
import com.emergency.embackend.entity.QuizType;
import com.emergency.embackend.exception.EmException;
import com.emergency.embackend.mapper.QuizTypeMapper;
import com.emergency.embackend.service.QuizTypeService;
import com.emergency.embackend.utils.RedisConstants;
import com.emergency.embackend.vo.QuizTypeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class QuizTypeServiceImpl implements QuizTypeService {
    @Autowired
    private QuizTypeMapper quizTypeMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<QuizTypeVO> getType() {
        List<QuizTypeVO> quizTypeVOS = new ArrayList<>();
        String key = RedisConstants.QUIZ_TYPE_KEY;
        Long size = stringRedisTemplate.opsForList().size(key);
        if (size == 0) {
            quizTypeVOS = quizTypeMapper.getType();
            if (quizTypeVOS == null) {
                throw new EmException("500", "类型查询为空");
            }
            //存入缓存中
            for (QuizTypeVO quizTypeVO : quizTypeVOS) {
                String s = JSONUtil.toJsonStr(quizTypeVO);
                stringRedisTemplate.opsForList().leftPush(key, s);
            }
            stringRedisTemplate.expire(key,RedisConstants.TYPE_TTL, TimeUnit.SECONDS);
            return quizTypeVOS;
        }
        for (int i = 0; i < size; i++) {
            String type = stringRedisTemplate.opsForList().leftPop(key);
            QuizTypeVO quizTypeVO = JSONUtil.toBean(type, QuizTypeVO.class);
            quizTypeVOS.add(quizTypeVO);
        }
        return quizTypeVOS;
    }

    @Override
    public void update(QuizType quizType) {
        quizTypeMapper.update(quizType);
        removeRedisQuizTypeKey();
    }

    @Override
    public void delete(Long typeId) {
        quizTypeMapper.delete(typeId);
        removeRedisQuizTypeKey();
    }

    @Override
    public void add(QuizType quizType) {
        quizTypeMapper.add(quizType);
        removeRedisQuizTypeKey();
    }
    private void removeRedisQuizTypeKey(){
        String key = RedisConstants.QUIZ_TYPE_KEY;
        stringRedisTemplate.delete(key);
    }

}
